package com.tanhua.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.Admin;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.AdminHolder;
import com.tanhua.mapper.AdminMapper;
import com.tanhua.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AdminMapper adminMapper;

    public ResponseEntity verification(String uuid, HttpServletResponse response) throws IOException {

        // 1 创建一张验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 100);

        //2 将验证码放入redis中   key:uuid   value:验证码内容
        String code = lineCaptcha.getCode();
        stringRedisTemplate.opsForValue().set("manager_code_"+uuid,code,5, TimeUnit.MINUTES);

        //3 写回创建很好的验证码即可
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);

        return ResponseEntity.ok(null);

    }

    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        //建议后台也要做验证
        //1 验证码不能为空
        if(StrUtil.isEmpty(verificationCode) || StrUtil.isEmpty(uuid)){
            throw new BusinessException("验证码不能为空");
        }
        //2 判断用户名密码为空
        if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password)){
            throw new BusinessException("用户名或密码为空");
        }
        //3 判断验证码是否正确
        String code = stringRedisTemplate.opsForValue().get("manager_code_" + uuid);
        if(StrUtil.isEmpty(code) || !verificationCode.equals(code)){
            throw new BusinessException("验证码错误");
        }

        //4 带着用户名去数据库查询
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);

        //5 判断用户是否存在
        if(admin==null){
            throw new BusinessException("该用户不存在");
        }

        //6 判断拿到的密码和页面传递的密码是否一致
        String md5Password = SecureUtil.md5(password);
        if(!admin.getPassword().equals(md5Password)){
            throw new BusinessException("密码错误！！！");
        }

        //删除code验证码
        stringRedisTemplate.delete("manager_code_"+uuid);


        //7 账号密码都没问题给apptoken
        String token = JwtUtil.createToken(admin.getPassword(), admin.getId(), "manager-tanhua");
        //优化2：将token和用户数据放入redis中
        String user_json = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set("manager_token_"+token,user_json,1,TimeUnit.DAYS);
        // 5 返回
        Map map=new HashMap();
        //优化3：将token响应给app保存
        map.put("token",token);
        return ResponseEntity.ok(map);

    }

    public Admin tokenfromUser(String token) {
        //根据token从redis中获取对象
        String json = stringRedisTemplate.opsForValue().get("manager_token_" + token);
        //将json转换成对象
        Admin admin = JSON.parseObject(json, Admin.class);
        //追加一天
        stringRedisTemplate.opsForValue().set("manager_token_"+token,json,1, TimeUnit.DAYS);
        return admin;
    }

    //登出
    public void logout() {
        Admin admin = AdminHolder.getAdmin();
        stringRedisTemplate.delete("manager_token_"+admin.getToken());
    }
}
